package com.java.simple.smallspring.jdbc.datasource;

import cn.hutool.core.lang.Assert;

import java.sql.Connection;
import java.util.Objects;

/**
 * @author zhoujunlin
 * @date 2022年11月19日 21:35
 * @desc
 */
public class ConnectionHolder {

    private ConnectionHandler connectionHandler;
    private Connection currentConnection;

    public ConnectionHolder(ConnectionHandler connectionHandler) {
        this.connectionHandler = connectionHandler;
    }

    public ConnectionHolder(Connection connection) {
        this.connectionHandler = new SimpleConnectionHandler(connection);
    }

    public ConnectionHandler getConnectionHandler() {
        return connectionHandler;
    }

    protected boolean hasConnection() {
        return Objects.nonNull(this.connectionHandler);
    }

    protected void setConnection(Connection connection) {
        if (Objects.nonNull(this.currentConnection)) {
            if (Objects.nonNull(this.connectionHandler)) {
                this.connectionHandler.releaseConnection(this.currentConnection);
            }
            this.currentConnection = null;
        }
        if (Objects.nonNull(connection)) {
            this.connectionHandler = new SimpleConnectionHandler(connection);
        } else {
            this.connectionHandler = null;
        }
    }

    protected Connection getConnection() {
        Assert.notNull(this.connectionHandler, "Active connection is required.");
        if (Objects.isNull(this.currentConnection)) {
            this.currentConnection = this.connectionHandler.getConnection();
        }
        return this.currentConnection;
    }

}
